const app = getApp();

Page({
    data: {
        userInfo: {},
        rightAnswer: [],
        selectedAnswer: [],
        rightCount: 0,
        rightIndex: [],
        score: 0,
        result: {},
        guessList: []
    },
    onLoad: function (options) {
        this.getGuessList();
        this.setData({
            userInfo: JSON.parse(options.userInfo),
            rightAnswer: JSON.parse(options.rightAnswer),
            selectedAnswer: JSON.parse(options.selectedAnswer)
        }, () => {
            // this.judgeResult();
            let result = this.diffArray(this.data.rightAnswer, this.data.selectedAnswer);
            let { notSameArr, notSameArrIndex, someArr, someArrIndex } = result;
            this.setData({
                score: someArrIndex.length * 10,
                result: result
            })
        })
        // 获取用户猜测列表
    },
    share() {
        console.log(this.data.userInfo);
        // this.onShareAppMessage();
    },
    onShareAppMessage: function () {
        return {
            title: '你的朋友等你来猜测哟！',
            path: `/pages/home/home?host=${this.data.userInfo.openid}`,
        }
    },
    // 查看答题详情
    lookDetail(evt) {
        let resultList = evt.currentTarget.dataset.result
        wx.navigateTo({
            url: `/pages/detail/detail?result=${JSON.stringify(resultList)}`,
        })
    },
    // 分析结果
    judgeResult() {
        if (this.data.rightAnswer) {
            this.data.rightAnswer.forEach((item, index) => {
                if (item === this.data.selectedAnswer[index]) {
                    this.setData({
                        rightCount: this.data.rightCount + 1,
                    })
                }
            })
        } else { }
    },
    // 数组diff
    diffArray(arr1 = [], arr2 = []) {
        let someArr = [];
        let someArrIndex = [];
        let notSameArr = [];
        let notSameArrIndex = [];
        arr1.forEach((item, index) => {
            if (arr2.includes(item)) {
                someArr.push(item);
                someArrIndex.push(index);
            } else {
                notSameArr.push(item);
                notSameArrIndex.push(index);
            }
        })
        return {
            someArr,
            someArrIndex,
            notSameArr,
            notSameArrIndex
        }
    },
    // 获取用户猜测列表
    getGuessList() {
        return new Promise((resolve, reject) => {
            app.cloud({
                name: 'user',
                data: {
                    $url: 'get_guess_list'
                }
            }).then(res => {
                this.setData({
                    guessList: res.resultList
                })
                resolve(res);
            }).catch(err => {
                reject(err);
            })
        })
    }
})